package com.ruoyi.refund.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.order.domain.Order;
import com.ruoyi.order.service.IOrderService;
import com.ruoyi.student.domain.DzStudent;
import com.ruoyi.student.service.IDzStudentService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.refund.domain.OrderRefund;
import com.ruoyi.refund.service.IOrderRefundService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 退费Controller
 *
 * @author ruoyi
 * @date 2024-02-26
 */
@RestController
@RequestMapping("/refund/refund")
public class OrderRefundController extends BaseController {
    @Autowired
    private IOrderRefundService orderRefundService;

    @Autowired
    private IOrderService orderService;

    /**
     * 查询退费列表
     */
    @PreAuthorize("@ss.hasPermi('refund:refund:list')")
    @GetMapping("/list")
    public TableDataInfo list(OrderRefund orderRefund) {
        startPage();
        List<OrderRefund> list = orderRefundService.selectOrderRefundList(orderRefund);
        return getDataTable(list);
    }

    /**
     * 导出退费列表
     */
    @PreAuthorize("@ss.hasPermi('refund:refund:export')")
    @Log(title = "退费", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, OrderRefund orderRefund) {
        List<OrderRefund> list = orderRefundService.selectOrderRefundList(orderRefund);
        ExcelUtil<OrderRefund> util = new ExcelUtil<OrderRefund>(OrderRefund.class);
        util.exportExcel(response, list, "退费数据");
    }

    /**
     * 获取退费详细信息
     */
    @PreAuthorize("@ss.hasPermi('refund:refund:query')")
    @GetMapping(value = "/{refundId}")
    public AjaxResult getInfo(@PathVariable("refundId") Long refundId) {
        return success(orderRefundService.selectOrderRefundByRefundId(refundId));
    }

    @Autowired
    private IDzStudentService dzStudentService;

    /**
     * 新增退费
     */
    @PreAuthorize("@ss.hasPermi('refund:refund:add')")
    @Log(title = "退费", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody OrderRefund orderRefund) {
        //获取订单号
        String orderId = orderRefund.getOrderId();
        //获取退课数量
        String refundCourseNumber = orderRefund.getRefundCourseNumber();

        //获取退课金额
        String refundAmount = orderRefund.getRefundAmount();

        //获取订单
        Order order = orderService.selectOrderByOrderId(Long.parseLong(orderId));

        //获取退款数量
        String droppedClassesNumber = order.getDroppedClassesNumber();
        int nowdroppedClassesNumber = Integer.parseInt(droppedClassesNumber) + Integer.parseInt(refundCourseNumber);


        //获取退款金额
        String MoneyDroppedTotal = order.getMoneyDroppedTotal();
        double nowMoneyDroppedTotal = Double.parseDouble(MoneyDroppedTotal) + Integer.parseInt(refundAmount);
        //设置退课数量
        order.setDroppedClassesNumber("" + nowdroppedClassesNumber);
        //设置退款金额
        order.setMoneyDroppedTotal("" + nowMoneyDroppedTotal);
        //获取订单课的数量
        String orderCourseNumber = order.getResidue();


        long long_refundCourseNumber = Long.parseLong(refundCourseNumber);
        long long_orderCourseNumber = Long.parseLong(orderCourseNumber);
        long now_refundCourseNumber = long_orderCourseNumber - long_refundCourseNumber;
        if (now_refundCourseNumber < 0) {
            return error("退款数量不能大于现有数量");

        }
        if (now_refundCourseNumber == 0) {
            order.setState("已完结");
        }
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String formattedDate = formatter.format(date);
        orderRefund.setRefundTime(formattedDate);
        //更新课时数量
        order.setResidue(String.valueOf(now_refundCourseNumber));
        //更新未确认收入
        String moneyUnconfirmed = order.getMoneyUnconfirmed();
        float nowMoneyUnconfirmed = Float.parseFloat(moneyUnconfirmed) - Float.parseFloat(refundAmount);
        order.setMoneyUnconfirmed("" + nowMoneyUnconfirmed);
        orderService.updateOrder(order);
        int i = orderRefundService.insertOrderRefund(orderRefund);


        Order orderquery = new Order();
        orderquery.setStudentId(order.getStudentId());
        orderquery.setOrderRemark10("0");

        List<Order> Orderlist = orderService.selectOrderList(orderquery);
        int value = 0;
        for (int w = 0; w < Orderlist.size(); w++) {
            String residue1 = Orderlist.get(w).getResidue();
            int intresidue1 = Integer.parseInt(residue1);
            //剩余课数量
            value = value + intresidue1;


        }
        //更新用户信息
        DzStudent dzStudent = dzStudentService.selectDzStudentById(Long.parseLong(order.getStudentId()));
        dzStudent.setRemainingClassHours("" + value);
        dzStudentService.updateDzStudent(dzStudent);


        return toAjax(i);
    }

    /**
     * 修改退费
     */
    @PreAuthorize("@ss.hasPermi('refund:refund:edit')")
    @Log(title = "退费", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody OrderRefund orderRefund) {
        return toAjax(orderRefundService.updateOrderRefund(orderRefund));
    }

    /**
     * 删除退费
     */
    @PreAuthorize("@ss.hasPermi('refund:refund:remove')")
    @Log(title = "退费", businessType = BusinessType.DELETE)
    @DeleteMapping("/{refundIds}")
    public AjaxResult remove(@PathVariable Long[] refundIds) {
        Long id = refundIds[0];
        OrderRefund orderRefund = orderRefundService.selectOrderRefundByRefundId(id);
        //获取退课数量
        String refundCourseNumber = orderRefund.getRefundCourseNumber();
        //获取实退金额
        String refundAmountReality = orderRefund.getRefundAmountReality();
        String orderId = orderRefund.getOrderId();
        Order order = orderService.selectOrderByOrderId(Long.parseLong(orderId));
        //获取退费总额
        String moneyDroppedTotal = order.getMoneyDroppedTotal();
        String residue = order.getResidue();
        String MoneyUnconfirmed = order.getMoneyUnconfirmed();
        Integer nowresidue = Integer.parseInt(residue) + Integer.parseInt(refundCourseNumber);

        double nowrefundAmountReality = Double.parseDouble(MoneyUnconfirmed) + Double.parseDouble(refundAmountReality);
        double nowmoneyDroppedTotal = Double.parseDouble(moneyDroppedTotal) - Double.parseDouble(refundAmountReality);
        order.setResidue("" + nowresidue);
        order.setState("进行中");
        order.setMoneyUnconfirmed("" + nowrefundAmountReality);
        order.setMoneyDroppedTotal("" + nowmoneyDroppedTotal);
        orderService.updateOrder(order);


        return toAjax(orderRefundService.deleteOrderRefundByRefundIds(refundIds));
    }


}
